package uy.com.tsi2G7.superbet.account;

import java.math.BigDecimal;
import java.rmi.RemoteException;

import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;

import uy.com.tsi2G7.superbet.account.dao.AccountNotFoundException;
import uy.com.tsi2G7.superbet.account.dao.AccountStore;
import uy.com.tsi2G7.superbet.account.dao.AccountStoreException;
import uy.com.tsi2G7.superbet.util.SpringContext;

@ManagedBean(name = "accountService")
@Stateless
public class AccountServiceEJB implements AccountService {	
	private AccountStore accountStore;
	
	public AccountStore getAccountStore() {
		if(accountStore==null)
			accountStore=(AccountStore) SpringContext.getApplicationContext().getBean("accountStore");
		return accountStore;
	}

	@Override
	public void storeAccount(Account account) throws RemoteException, AccountStoreException {
		getAccountStore().storeAccount(account);
	}

	@Override
	public void activateAccount(String user) throws RemoteException, AccountStoreException {
		try{
			//Buscamos la cuenta
			Account account = getAccountStore().getAccount(user);
			if (account.getState().equals(AccountState.ACTIVATED)){
				throw new AccountStoreException("Cuenta ya activada");
			}
			//Cambiamos estado
			account.setState(AccountState.ACTIVATED);
			//Actualizamos la cuenta
			getAccountStore().storeAccount(account);
		}catch(RemoteException e){
			throw e;
		}catch(AccountNotFoundException e){
			throw new AccountStoreException("La cuenta no existe");
		}
	}

	@Override
	public void debitBet(BigDecimal amount, String userId) throws RemoteException, AccountNotFoundException, InsufficientFoundException {
		
		Account account = getAccountStore().getAccount(userId);
		if(account.getBalance().compareTo(amount)<0)
			throw new InsufficientFoundException();
		getAccountStore().addMovement(userId,amount.negate(),MovementType.BET);
	}

	@Override
	public void creditBet(BigDecimal amount, String userId)
			throws RemoteException, AccountNotFoundException{
		getAccountStore().addMovement(userId,amount,MovementType.BET);
		
	}

	@Override
	public void creditAmount(BigDecimal amount, String userId) throws RemoteException, AccountNotFoundException {
		getAccountStore().addMovement(userId, amount, MovementType.CREDIT);
		
	}
	
	@Override
	public void  debitAmount(BigDecimal amount, String userId)throws RemoteException, AccountNotFoundException{
		getAccountStore().addMovement(userId,amount.multiply(new BigDecimal(-1)),MovementType.DEBIT);		
	}
	
	@Override
	public Account getAccount(String userId) throws RemoteException, AccountNotFoundException{		
		return getAccountStore().getAccount(userId);		
	}

}
